package leetcode;

import util.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Project : algorithm-learning-java
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/1/26 16:37
 */
public class Q0637 {
    List<Long> num = new ArrayList<>();
    List<Long> sum = new ArrayList<>();
    List<Double> res = new ArrayList<>();

    private void dfs(TreeNode node, int layer) {
        if (node == null) return;
        if (layer > num.size()) {
            num.add(0L);
            sum.add(0L);
        }
        num.set(layer - 1, num.get(layer - 1) + 1);
        sum.set(layer - 1, sum.get(layer - 1) + node.val);
        dfs(node.left, layer + 1);
        dfs(node.right, layer + 1);
    }

    public List<Double> averageOfLevels(TreeNode root) {
        dfs(root, 1);
        for (int i = 0; i < num.size(); i++) {
            res.add(sum.get(i) * 1.0 / num.get(i));
        }
        return res;
    }
}
